<template>
  <div class="profile-container">
    <el-card class="profile-header" v-loading="loading">
      <div class="header-content">
        <div class="avatar-section">
          <div class="avatar-wrapper" @click="openAvatarUpload">
            <el-avatar :size="120" :src="userInfo.avatar ||
              'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
              " class="user-avatar" />
            <div class="avatar-mask">
              <el-icon>
                <Camera />
              </el-icon>
              <span>更换头像</span>
            </div>
          </div>
          <div class="avatar-info">
            <h2 class="user-name">
              {{ userInfo.nickname || userInfo.username }}
              <el-tag :type="getRoleType(userInfo.role)" size="small" style="margin-left: 12px">
                {{ getRoleText(userInfo.role) }}
              </el-tag>
            </h2>
            <p class="user-username">@{{ userInfo.username }}</p>
            <div class="user-meta">
              <span>
                <el-icon>
                  <Message />
                </el-icon>
                {{ userInfo.email }}
              </span>
              <span>
                <el-icon>
                  <Calendar />
                </el-icon>
                加入于 {{ formatDate(userInfo.created_at) }}
              </span>
            </div>
          </div>
        </div>

        <div class="header-actions">
          <el-button type="primary" @click="openEditDialog" :icon="'Edit'">
            编辑资料
          </el-button>
          <el-button @click="openPasswordDialog" :icon="'Lock'">
            修改密码
          </el-button>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20" class="info-cards">
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-icon" style="
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            ">
            <el-icon>
              <User />
            </el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">账号状态</div>
            <div class="stat-value">
              <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
                {{ userInfo.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-icon" style="
              background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            ">
            <el-icon>
              <Key />
            </el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">用户ID</div>
            <div class="stat-value">#{{ userInfo.id }}</div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-icon" style="
              background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            ">
            <el-icon>
              <Star />
            </el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">权限级别</div>
            <div class="stat-value">
              {{ userInfo.role === 'admin' ? '超级管理员' : '普通用户' }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>📋 详细信息</span>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">{{
          userInfo.id
        }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{
          userInfo.username
        }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{
          userInfo.nickname || '未设置'
        }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{
          userInfo.email
        }}</el-descriptions-item>
        <el-descriptions-item label="角色">
          <el-tag :type="getRoleType(userInfo.role)">{{
            getRoleText(userInfo.role)
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
            {{ userInfo.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          formatDate(userInfo.created_at)
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{
          formatDate(userInfo.updated_at)
        }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 编辑资料对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑个人资料" width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="昵称">
          <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProfile">保存</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="450px">
      <el-form :model="passwordForm" label-width="90px">
        <el-form-item label="原密码">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" show-password />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码（至少6位）" show-password />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changePassword">确认修改</el-button>
      </template>
    </el-dialog>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="更换头像" width="450px">
      <div class="upload-container">
        <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="() => false"
          :on-change="handleAvatarSuccess" :disabled="uploadingAvatar" accept="image/*">
          <div v-if="uploadedImageUrl" class="avatar-preview">
            <img :src="uploadedImageUrl" class="preview-image" />
          </div>
          <div v-else class="upload-placeholder">
            <el-icon class="upload-icon" :class="{ uploading: uploadingAvatar }">
              <Loading v-if="uploadingAvatar" />
              <Plus v-else />
            </el-icon>
            <div class="upload-text">
              {{ uploadingAvatar ? '上传中...' : '点击选择图片' }}
            </div>
            <div v-if="uploadingAvatar" class="upload-progress">
              <el-progress :percentage="uploadProgress" :stroke-width="6" />
            </div>
            <div v-else class="upload-hint">
              支持 JPG、PNG 格式，大小不超过 2MB
            </div>
          </div>
        </el-upload>
      </div>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUploadedAvatar" :disabled="!uploadedImageUrl || uploadingAvatar"
          :loading="uploadingAvatar">
          保存头像
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Loading } from '@element-plus/icons-vue'
import {
  getUserInfo,
  updateProfile as updateProfileApi,
  changePassword as changePasswordApi
} from '@/api/auth'
import { uploadFile as uploadFileToQiniu } from '@/api/upload'

// 用户信息
const userInfo = ref({
  id: 0,
  username: '',
  email: '',
  role: '',
  nickname: '',
  avatar: '',
  created_at: '',
  status: 1
})

// 加载状态
const loading = ref(true)

// 编辑对话框
const editDialogVisible = ref(false)
const editForm = ref({
  nickname: '',
  email: ''
})

// 修改密码对话框
const passwordDialogVisible = ref(false)
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 加载用户信息
const loadUserInfo = async () => {
  loading.value = true
  try {
    const result = await getUserInfo()
    if (result.success) {
      userInfo.value = result.data
      editForm.value = {
        nickname: result.data.nickname || '',
        email: result.data.email || ''
      }
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
    ElMessage.error('加载失败，请重试')
  } finally {
    loading.value = false
  }
}

// 打开编辑对话框
const openEditDialog = () => {
  editDialogVisible.value = true
}

// 保存个人信息
const saveProfile = async () => {
  try {
    const result = await updateProfileApi({
      nickname: editForm.value.nickname,
      email: editForm.value.email
    })

    if (result.success) {
      ElMessage.success('个人信息已更新')
      editDialogVisible.value = false

      // 更新本地存储
      const user = JSON.parse(localStorage.getItem('adminUser') || '{}')
      user.nickname = result.data.nickname
      user.email = result.data.email
      localStorage.setItem('adminUser', JSON.stringify(user))

      // 重新加载
      loadUserInfo()
    } else {
      ElMessage.error(result.message || '更新失败')
    }
  } catch (error) {
    console.error('更新资料失败:', error)
    ElMessage.error('更新失败，请重试')
  }
}

// 打开修改密码对话框
const openPasswordDialog = () => {
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  passwordDialogVisible.value = true
}

// 修改密码
const changePassword = async () => {
  if (!passwordForm.value.oldPassword || !passwordForm.value.newPassword) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    ElMessage.error('两次输入密码不一致')
    return
  }

  if (passwordForm.value.newPassword.length < 6) {
    ElMessage.error('密码长度至少6个字符')
    return
  }

  try {
    const result = await changePasswordApi({
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword
    })

    if (result.success) {
      ElMessage.success('密码修改成功，请重新登录')
      passwordDialogVisible.value = false

      // 清除登录信息，跳转到登录页
      setTimeout(() => {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminUser')
        window.location.href = '/login'
      }, 1500)
    } else {
      ElMessage.error(result.message || '修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改失败，请重试')
  }
}

// 头像上传相关
const uploadDialogVisible = ref(false)
const uploadedImageUrl = ref('')
const uploadingAvatar = ref(false)
const uploadProgress = ref(0)

// 打开头像上传对话框
const openAvatarUpload = () => {
  uploadedImageUrl.value = ''
  uploadProgress.value = 0
  uploadDialogVisible.value = true
}

// 处理头像上传
const handleAvatarSuccess = async (uploadFile) => {
  const file = uploadFile.raw

  // 验证文件
  if (!beforeAvatarUpload(file)) {
    return
  }

  uploadingAvatar.value = true
  uploadProgress.value = 0

  try {
    // 调用后端上传接口
    const result = await uploadFileToQiniu(file, (percent) => {
      uploadProgress.value = percent
    })

    if (result.success) {
      uploadedImageUrl.value = result.data.url
      ElMessage.success('图片上传成功！请点击保存按钮更新头像')
    } else {
      ElMessage.error('上传失败，请重试')
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('上传失败：' + (error.message || '请重试'))
  } finally {
    uploadingAvatar.value = false
  }
}

// 上传前验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 保存上传的头像
const saveUploadedAvatar = async () => {
  if (!uploadedImageUrl.value) {
    ElMessage.warning('请先选择图片')
    return
  }

  try {
    const result = await updateProfileApi({
      avatar: uploadedImageUrl.value
    })

    if (result.success) {
      ElMessage.success('头像更新成功！')
      uploadDialogVisible.value = false
      uploadedImageUrl.value = ''

      // 更新本地存储
      const user = JSON.parse(localStorage.getItem('adminUser') || '{}')
      user.avatar = result.data.avatar
      localStorage.setItem('adminUser', JSON.stringify(user))

      // 重新加载
      loadUserInfo()
    } else {
      ElMessage.error(result.message || '更新失败')
    }
  } catch (error) {
    console.error('头像更新失败:', error)
    ElMessage.error('更新失败，请重试')
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 获取角色显示
const getRoleText = (role) => {
  const roleMap = {
    admin: '管理员',
    user: '普通用户'
  }
  return roleMap[role] || role
}

// 获取角色标签类型
const getRoleType = (role) => {
  return role === 'admin' ? 'danger' : 'success'
}

onMounted(() => {
  loadUserInfo()
})
</script>


<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
}

/* 头部卡片 */
.profile-header {
  margin-bottom: 20px;
  border-radius: 12px;
  overflow: hidden;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.avatar-section {
  display: flex;
  gap: 24px;
  align-items: center;
}

.avatar-wrapper {
  position: relative;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
}

.user-avatar {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border: 4px solid #f0f2f5;
  transition: all 0.3s;
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 14px;
  gap: 4px;
}

.avatar-wrapper:hover .avatar-mask {
  opacity: 1;
}

.avatar-wrapper:hover .user-avatar {
  transform: scale(1.05);
}

.avatar-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-name {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  color: #1a1a1a;
  display: flex;
  align-items: center;
}

.user-username {
  margin: 0;
  font-size: 16px;
  color: #6b7280;
}

.user-meta {
  display: flex;
  gap: 24px;
  font-size: 14px;
  color: #9ca3af;
  margin-top: 8px;
}

.user-meta span {
  display: flex;
  align-items: center;
  gap: 6px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.info-cards {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.stat-card :deep(.el-card__body) {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 24px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 28px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

/* 详细信息卡片 */
.detail-card {
  border-radius: 12px;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
}

.detail-card :deep(.el-descriptions__label) {
  font-weight: 500;
  color: #374151;
}

.detail-card :deep(.el-descriptions__content) {
  color: #1a1a1a;
}

/* 头像上传 */
.upload-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.avatar-uploader {
  width: 200px;
}

.avatar-preview {
  width: 200px;
  height: 200px;
  border-radius: 12px;
  overflow: hidden;
  border: 2px dashed #d9d9d9;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-preview:hover {
  border-color: #409eff;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  width: 200px;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.upload-placeholder:hover {
  border-color: #409eff;
  background: #f0f7ff;
}

.upload-icon {
  font-size: 48px;
  color: #8c939d;
  margin-bottom: 12px;
}

.upload-text {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  text-align: center;
  padding: 0 20px;
}

.upload-progress {
  width: 100%;
  padding: 0 20px;
  margin-top: 12px;
}

.upload-icon.uploading {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>
